import os

from conf import settings
from lib import common
from db import models


@common.login_auth
def check_movie(conn, back_dic):
	# print(back_dic)
	movie_list = models.Movie.select(file_md5=back_dic['file_md5'])
	if movie_list:
		send_dic = {"flag": False, "msg": "电影已存在..."}
	else:
		send_dic = {"flag": True, "msg": "可以上传..."}
	common.send_msg(conn, send_dic)


@common.login_auth
def upload_movie(conn, back_dic):
	# "type": "upload_movie", "session": user_dic['cookie'], "name": movie_name,
	# "file_md5": movie_md5, "is_free": is_free
	user = models.Movie(name=back_dic['name'], path=back_dic['path'], is_free=int(back_dic['is_free']), is_delete=0, file_md5=back_dic['file_md5'], upload_time=common.get_time(), user_id=back_dic["user_id"])
	recv_size = 0
	path = os.path.join(settings.BASE_MOVIE_DB, back_dic["name"])

	with open(path, 'wb') as f:
		# print(back_dic["movie_size"])
		while recv_size < back_dic["movie_size"]:
			# print(recv_size)
			recv_data = conn.recv(1024)
			f.write(recv_data)
			recv_size += len(recv_data)
	user.save()
	send_dic = {'flag': True, 'msg': '上传成功...'}
	common.send_msg(conn, send_dic)


@common.login_auth
def delete_movie(conn, back_dic):
	os.remove(back_dic['path'])
	send_dic = {"flag": True, 'msg': "删除成功..."}
	common.send_msg(conn, send_dic)



